package com.miaostars.level.utils;

import org.bukkit.entity.Player;
import java.util.*;
import java.util.concurrent.*;

public class CPSValidator {
    private static final Map<UUID, Queue<Long>> clickRecords = new ConcurrentHashMap<>();
    private static final int MAX_CPS = 20; // 默认最大CPS
    private static final int MIN_CLICK_INTERVAL = 50; // 最小点击间隔（毫秒）

    // 校验点击是否合法
    public static boolean isValidClick(Player player) {
        UUID uuid = player.getUniqueId();
        Queue<Long> timestamps = clickRecords.computeIfAbsent(uuid, k -> new ConcurrentLinkedQueue<>());
        long now = System.currentTimeMillis();

        // 移除1秒前的记录
        while (!timestamps.isEmpty() && now - timestamps.peek() > 1000) {
            timestamps.poll();
        }

        // 检测是否超过阈值
        if (timestamps.size() >= MAX_CPS) return false;
        if (!timestamps.isEmpty() && now - timestamps.peek() < MIN_CLICK_INTERVAL) return false;

        timestamps.add(now);
        return true;
    }

    // 重置玩家点击记录
    public static void resetPlayerClicks(UUID uuid) {
        clickRecords.remove(uuid);
    }

    // 从配置加载参数（需在主插件初始化时调用）
    public static void loadConfig(int maxCPS, int minInterval) {
        MAX_CPS = maxCPS;
        MIN_CLICK_INTERVAL = minInterval;
    }
}